// import axios from 'axios'
/* eslint-disable */
import qs from 'qs'
import {message} from 'antd'

const baseUrl = 'https://amojito.cn/'
// http://localhost:8080/

axios.defaults.baseURL = baseUrl
axios.defaults.withCredentials = true

axios.interceptors.request.use((config) => {
    if (config.method === 'post') {
        let data = qs.parse(config.data)
        config.params = {
            ...config.params
        }
        config.data = qs.stringify({
            ...data
        })
    }
    return config;
}, (error) => {
    return Promise.reject(error.toString());
})

axios.interceptors.response.use((res) => {
    if (res.data.code === 0) {
        return res.data.content
    } else if (res.data.code === 304) {
        // setTimeout(() => {
        //     window.location.href = '/login'
        // }, 1500)
        //移到获取用户信息接口
        return Promise.reject(304)
    } else {
        return Promise.reject(res.data.message)
    }
}, (error) => {
    if(error.toString().indexOf('Cancel') === -1)
    return Promise.reject(error.toString())
})

function request(params){
    return new Promise((resolve, reject) => {
        axios({
            url: params.url || '',
            method: params.method || 'post',
            params: params.params || {},
            data: params.data || {},
            headers: {
                'Content-Type': params.contentType || 'application/x-www-form-urlencoded'
            },
            cancelToken: new axios.CancelToken((c) => {
                params.cancelToken && params.cancelToken(c)
            }),
            paramsSerializer: function (param) {
                return qs.stringify(param, {
                    arrayFormat: 'repeat'
                })
            }
        }).then(res => {
            resolve(res)
        }).catch(err => {
            console.log(err || '请求异常')
            if(err === 304){
                message.error({
                    content: '即将重新登录……',
                    duration: 1.5,
                    key: 'loginOverTime' //让这个提示全局唯一 不会出现多个
                })
            }else{
                message.warning(err || '请求异常')
            }
            reject(err)
        })
    })
}

export {
    request,
	baseUrl
}
/* eslint-disable */